package com.example.myapplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.myapplication.adapter.NoteListAdapter;
import com.example.myapplication.database.DatabaseHelper;
import com.example.myapplication.databinding.ActivityMainBinding;
import com.example.myapplication.model.Note;
import com.example.myapplication.ui.EditActivity;
import com.example.myapplication.ui.TodoActivity;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private DatabaseHelper databaseHelper;
    private NoteListAdapter noteListAdapter;

    private static final int EDIT_REQUEST_CODE = 1001;  // 请求码
    private List<String> categoryList;  // 分类列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        databaseHelper = new DatabaseHelper(this);
        noteListAdapter = new NoteListAdapter();

        binding.listRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        binding.listRv.setAdapter(noteListAdapter);
        binding.listRv.setLayoutManager(new LinearLayoutManager(this));

        // 初始化笔记列表
        updateNoteList();

        // 添加分类 Spinner
        initializeCategorySpinner();

        // 点击添加按钮跳转到编辑页面
        binding.addIv.setOnClickListener(view -> {
            Intent intent = new Intent(MainActivity.this, EditActivity.class);
            startActivityForResult(intent, EDIT_REQUEST_CODE);
        });

        // 添加 SearchView 的监听器
        binding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchNotes(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                searchNotes(newText);
                return true;
            }
        });
        // 在 MainActivity 的 onCreate 方法中为 shiftIv 设置点击监听
        binding.shiftIv.setOnClickListener(view -> {
            Intent intent = new Intent(MainActivity.this, TodoActivity.class);
            startActivity(intent);
        });

    }

    private void initializeCategorySpinner() {
        categoryList = new ArrayList<>();
        // 获取所有分类
        List<String> categories = databaseHelper.getAllCategories();
        categoryList.add("全部");  // 默认类别
        categoryList.addAll(categories);
        categoryList.add("添加分类"); // 添加分类选项

        // 创建 Spinner 的适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categoryList);
        binding.categorySpinner.setAdapter(adapter);

        // 设置 Spinner 的选择监听器
        binding.categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCategory = categoryList.get(position);
                if ("添加分类".equals(selectedCategory)) {
                    // 弹出对话框添加新分类
                    showAddCategoryDialog(adapter);
                } else {
                    Toast.makeText(MainActivity.this, "Selected Category: " + selectedCategory, Toast.LENGTH_SHORT).show();

                    if (!"全部".equals(selectedCategory)) {
                        filterNotesByCategory(selectedCategory);
                    } else {
                        updateNoteList();  // 显示所有笔记
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });
    }

    // 显示添加分类的对话框
    private void showAddCategoryDialog(ArrayAdapter<String> adapter) {
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加新分类");

        // 输入框
        final EditText input = new EditText(this);
        input.setHint("请输入分类名称");
        builder.setView(input);

        // 设置对话框按钮
        builder.setPositiveButton("确定", (dialog, which) -> {
            String newCategory = input.getText().toString().trim();
            if (!newCategory.isEmpty()) {
                // 检查分类是否已存在
                if (!categoryList.contains(newCategory)) {
                    // 添加分类到数据库和列表
                    databaseHelper.addCategory(newCategory); // 假设有一个 addCategory 方法
                    categoryList.add(categoryList.size() - 1, newCategory); // 添加到 "添加分类" 前
                    adapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, "分类已添加: " + newCategory, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "分类已存在！", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MainActivity.this, "分类名称不能为空！", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        // 显示对话框
        builder.show();
    }


    private void searchNotes(String query) {
        List<Note> noteList = databaseHelper.search(query);
        noteListAdapter.update(noteList);
    }

    private void filterNotesByCategory(String category) {
        List<Note> filteredNotes = databaseHelper.getNotesByCategory(category);
        noteListAdapter.update(filteredNotes);
    }

    private void updateNoteList() {
        List<Note> noteList = databaseHelper.findAll();
        noteListAdapter.update(noteList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == EDIT_REQUEST_CODE) {
            // 当编辑返回时，更新笔记列表
            updateNoteList();
        }
    }
}
